﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace DataAccess
{
    public class ConnectDatabase
    {
        private static String conString = "Server = localhost;Database = hospital;Port = 3306;User ID = root;Password=;Charset = utf8";
        public DataTable ExcuteQuery(String sql)
        {
              MySqlConnection conn = new MySqlConnection(conString);
              conn.Open();
              Console.WriteLine("Ket noi thanh cong");
            //Tao doi tuong thuc thi lenh ket noi
            MySqlCommand cmd = new MySqlCommand(sql,conn);
            //Tao doi tuong chua du lieu voi cmd da tao
            MySqlDataAdapter dt = new MySqlDataAdapter(cmd);
            //Tra ve ket qua la bang chua csdl
            DataTable kq = new DataTable();
            dt.Fill(kq);
            conn.Close();
            return kq;
        }
        public DataTable ExcuteQuery(String sql, String[] name, object[] value, int parameterNumber)
        {
            MySqlConnection conn = new MySqlConnection(conString);
            conn.Open();
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            for (int i = 0; i < parameterNumber; i++)
            {
                cmd.Parameters.AddWithValue(name[i], value[i]);
            }
            MySqlDataAdapter dt = new MySqlDataAdapter(cmd);
            //Tra ve ket qua la bang chua csdl
            DataTable kq = new DataTable();
            dt.Fill(kq);
            conn.Close();
            return kq;
        }
        //Ham insert,update,delete
        public Boolean ExcuteNonQuery(String sql,String [] name,object [] value,int parameterNumber) {
            MySqlConnection conn = new MySqlConnection(conString);
            conn.Open();
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            for (int i = 0; i < parameterNumber; i++) {
                cmd.Parameters.AddWithValue(name[i],value[i]);
            }
                try
                {
                    cmd.ExecuteNonQuery();
                    conn.Close();
                    return true;
                }
                catch
                {
                    return false;
                }
           
        }
        public Boolean ExcuteNonQuery(String sql)
        {
            MySqlConnection conn = new MySqlConnection(conString);
            conn.Open();
            MySqlCommand cmd = new MySqlCommand(sql, conn);
            try
            {
                cmd.ExecuteNonQuery();
                conn.Close();
                return true;
            }
            catch
            {
                return false;
            }

        }
    }       
    }

